<?php

namespace App\Actor;

use App\Model\ChatModel;
use EasySwoole\Actor\AbstractActor;
use EasySwoole\Actor\ActorConfig;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\RedisPool\RedisPool;
use Throwable;

class ChatActor extends AbstractActor
{
    private $fd;
    private $userId;
    private $lastHeartBeat;

    public static function configure(ActorConfig $actorConfig)
    {
        // TODO: Implement configure() method.
        $actorConfig->setActorName('ChatActor');
        $actorConfig->setWorkerNum(3);
    }

    protected function onStart()
    {
        // TODO: Implement onStart() method.
        $this->lastHeartBeat = time();

        $this->fd = $this->getArg()['fd'];
        $this->userId = $this->getArg()['userId'];

        // 记录到table
        ChatManager::addChat(new ChatBean([
            'actorId' => $this->actorId(),
            'fd' => $this->fd,
            'uid' => $this->userId,
        ]));

        //RedisPool::defer('redis')->set("user_" . $this->userId, $this->fd, 10);

        $userid = $this->userId;
        // 创建一个定时器，如果3秒没有接收到消息，自动下线
        $this->tick(5 * 1000, function () use($userid) {
            if (time() - $this->lastHeartBeat > 6) {
                $this->exit(-1);
            }
        });
    }

    protected function onMessage($msg)
    {
        // TODO: Implement onMessage() method.
        if($msg instanceof Command){
            switch ($msg->getCommand()){
                case $msg::WS_PING:
                    $this->lastHeartBeat = time();
                    $this->fd = $msg->getFd();
                    //$this->userId = $msg->getUserId();
                    ChatManager::updateChatInfo($this->userId, ['fd' => $this->fd]);
                    break;
                case $msg::WS_MSG:
                    $params = $msg->getParams();
                    $this->sendMsg($params);
                    break;
            }
        }

    }

    protected function onExit($arg)
    {
        // TODO: Implement onExit() method.
        if ($arg == -1) {
            if (ServerManager::getInstance()->getSwooleServer()->exist($this->fd)) {
                ServerManager::getInstance()->getSwooleServer()->push($this->fd, "exit");
                ServerManager::getInstance()->getSwooleServer()->close($this->fd);
            }
        }
        ChatManager::deleteChat($this->userId);
    }

    protected function onException(Throwable $throwable)
    {
        // TODO: Implement onException() method.
    }

    /**
     * @param $param
     */
    protected function sendMsg($param)
    {
        $ufd = $this->fd;
        TaskManager::getInstance()->async(function () use ($ufd, $param) {
            //给指定客户推送消息，socket id可以使用redis存储;
            ServerManager::getInstance()->getSwooleServer()->push($ufd, json_encode($param));
        });
    }
}